package com.kuangjia.student_ems.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuangjia.student_ems.dto.AiChatResponse;
import com.kuangjia.student_ems.service.AiService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * AI服务实现类
 * 实现与DeepSeek API的交互
 */
@Service
public class AiServiceImpl implements AiService {

    private static final Logger logger = Logger.getLogger(AiServiceImpl.class.getName());
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 直接硬编码DeepSeek API的URL和密钥
    private static final String API_URL = "https://api.deepseek.com";
    private static final String API_ENDPOINT = "/v1/chat/completions";
    private static final String API_KEY = "sk-671ac7783bdd43a0b2f420af29b382bc";
    private static final String MODEL = "deepseek-chat";
    
    
    @Override
    public AiChatResponse generateResponse(String question) {
        try {
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + API_KEY);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", MODEL);
            
            // 构建消息数组
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", question);
            
            requestBody.put("messages", new Object[]{userMessage});
            requestBody.put("temperature", 0.7);
            requestBody.put("max_tokens", 1000);
            
            // 发送请求
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            String fullUrl = API_URL + API_ENDPOINT;
            logger.info("发送请求到: " + fullUrl);
            String responseBody = restTemplate.postForObject(fullUrl, request, String.class);
            
            // 解析响应
            JsonNode rootNode = objectMapper.readTree(responseBody);
            JsonNode choicesNode = rootNode.path("choices");
            
            if (choicesNode.isArray() && choicesNode.size() > 0) {
                String answer = choicesNode.get(0).path("message").path("content").asText();
                return new AiChatResponse(answer);
            } else {
                logger.warning("DeepSeek API响应格式异常: " + responseBody);
                return new AiChatResponse("抱歉，我无法理解您的问题，请尝试重新表述。");
            }
            
        } catch (Exception e) {
            logger.severe("调用DeepSeek API时发生错误: " + e.getMessage());
            return new AiChatResponse("抱歉，服务暂时不可用，请稍后再试。");
        }
    }
    

}